<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Task
 *
 * @author Administrator
 */
vendor('Snoopy.Snoopy#class');
vendor('simplehtmldom.simple_html_dom');
import('@.Service.TypeService');
import('@.Service.AppService');
import('@.Service.NewsService');
import('@.Service.ConfigService');
import('@.Service.AppTopService');
import('@.Service.SubjectService');
import('@.Filter.SecurityAction');
import('@.Util.ConstantUtil');

class TaskAction extends SecurityAction {

    function task() {


        $this->assign('content', 'task');
        $this->display('Admin:global');
    }

    function loadHtml() {
        header("Content-type:text/html; charset=utf-8");
        //读取数据库中的标识
        //$loadHtmlFlagValue = D("config")->field("value")->where("name = 'load_html_flag'")->find();
        //if (0 == $loadHtmlFlagValue) {
        //未抓取
        //}
//        $url = ;
//        dump($loadHtmlFlag);
//        $this->parseHtml($url);
        //拉取数据
        //写数据
//        $this->writeUrl();
//        ($this->matchDateTime('2011-3-4 12:34', '2011-3-3 12:34'));
//        $html = file_get_html('http://www.iapps.im/archives/120#more-120');
//
//        $html->getElementById("ckepop")->clear();
//        $html->getElementById("wumiiLikeRecBtnDiv")->clear();
////        echo $html;
//        $d = array_shift($html->find("#colLeft div.postRight"));
//
//        $d->children(7)->clear();
//        $d->children(3)->clear();
//        $d->children(2)->clear();
//        echo count($html->find("a href^=['http://click.linksynergy.com']"));

        $app = $this->getContent('http://www.iapps.im/archives/20016#more-20016');

        echo $app['content'];
    }

    private function loadUrl($host) {
        $html = file_get_html($host);
        $div = $html->find("#colLeft div.postRight");
        $r = array();
        foreach ($div as $d) {
            array_push($r, $d->children(2)->children(0)->attr['href']);
        }
        return $r;
    }

    function writeUrl() {
        //当天已经拉取完毕
        if ($this->isLoad()) {
            //进行本地发布
            $this->ajaxReturn(-1);
        }
        $page = $_POST["page"];

        $host = ConstantUtil::$LOAD_APP_URL . $page;

        $r = $this->loadUrl($host);

        $url_table = D('urls');
        $data = array();
        foreach ($r as $u) {
            if ($this->isHas($url_table, $u)) {
                array_push($data, array('url' => $u, 'load' => 0, 'load_over' => 0, 'datetime' => date('Y-m-d H:m:s'), 'type' => 'app'));
            }
        }
        if (!empty($data)) {
            $url_table->addAll($data);
        }

        if (-1 == --$page) {
            //更新这一时段的拉取标识
            $this->modifyLoadConfig();
        }
        $this->ajaxReturn(array('page' => $page, 'addCount' => count($data)));
    }

    /**
     * 抓取新闻链接
     */
    function loadNewsHtml() {
        $page = $_POST['page'];
        $newsService = new NewsService();

        //抓取3种类型新闻 {0}.html
        $count = 0;
        $host = ConstantUtil::$LOAD_NEW_URL . $page . '.html';
        $count += $newsService->writeUrl($host, 'new');
        $host = ConstantUtil::$LOAD_PRICE_URL . $page . '.html';
        $count += $newsService->writeUrl($host, 'price');
        $host = ConstantUtil::$LOAD_REVIEWS_URL . $page . '.html';
        $count += $newsService->writeUrl($host, 'reviews');


        $this->ajaxReturn(array('page' => --$page, 'count' => $count), ConstantUtil::$IS_LOAD_OVER);
    }

    /**
     * 发布新闻
     */
    function releaseNews() {
        //清空新闻中的缓存
        F(ConstantUtil::$NEWS_INDEX, NULL);

        $newsService = new NewsService();
        if (!$newsService->releaseNews()) {
            $this->ajaxReturn(false, ConstantUtil::$IS_RELEASE_OVER);
        } else {
            $this->ajaxReturn(true);
        }
    }

    /**
     * 排行榜
     */
    function releaseTop() {
        $appTopService = new AppTopService();

        $this->ajaxReturn($appTopService->releaseTop());
    }

    /**
     * 再次免费
     */
    function releaseFreeAgain() {
        ignore_user_abort();
        //修改最大执行时间
        ini_set("max_execution_time", 6 * 60); // s 3 分钟
        //修改此次的最大运行内存
        ini_set("memory_limit", 1048576000 / 10); // Byte 100 兆

        S(ConstantUtil::$INDEX_FREE_AGAIN, NULL);
        $appService = new AppService();
        $this->ajaxReturn($appService->listFreeAgain());
    }

    function loadSubject() {
        $subjectService = new SubjectService();
        //修改最大执行时间
        ini_set("max_execution_time", 3 * 60); // s 3 分钟
        //修改此次的最大运行内存
        ini_set("memory_limit", 1048576000 / 10); // Byte 100 兆
        //抓取顶级Subject链接
        $subjectService->loadSubjectAllUrl(ConstantUtil::$LOAD_SUBJECT_URL);
        //抓取二级Subject链接
        $subjectService->loadChildAllSubjectUrl();

        //抓取SubjectContent内容

        $result = $subjectService->loadSubjectContent();
        if (ConstantUtil::$IS_RELEASE_OVER == $result) {
            $this->ajaxReturn(null, ConstantUtil::$IS_RELEASE_OVER, 0);

            return;
        }

        $this->ajaxReturn($result);
    }

    /**
     * 本地发布App
     */
    function releaseApp() {
        if ($this->isRelease()) {
            $this->ajaxReturn(true);
            return;
        }
        //修改最大执行时间
        ini_set("max_execution_time", 3 * 60); // s 3 分钟
        //修改此次的最大运行内存
        ini_set("memory_limit", 1048576000 / 10); // Byte 100 兆

        $appService = new AppService();
        if (!$appService->releaseApps()) {
            $this->ajaxReturn(false);
            return;
        }

        $this->ajaxReturn(true);
    }

    /**
     * 当前时间是否需要进行发布
     */
    private function isRelease() {
        $today = date('d H');

        $configService = new ConfigService();
        $value = $configService->getConfigValue('release_last_data');

        return $today == $value;
    }

    /**
     * 更新拉取标识
     */
    private function modifyLoadConfig() {
        $config = D('config');
        $today = date('d H');
        $todayLoadOver = $config->where(array('name' => 'today_load_over'))->find();
        $lastDate = $config->where(array('name' => 'last_date'))->find();


        $todayLoadOver['value'] = 1;
        $lastDate['value'] = $today;

        $config->save($todayLoadOver);
        $config->save($lastDate);
    }

    /**
     * 是否已经拉取完毕
     */
    private function isLoad() {
        $config = D('config');
        $today = date('d H');

        $todayLoadOver = $config->where(array('name' => 'today_load_over'))->find();
        $lastDate = $config->where(array('name' => 'last_date'))->find();
        if (0 == $todayLoadOver['value']) {
            return false;
        }

        if ($today != $lastDate['value']) {
            return false;
        }
        return true;
    }

    /**
     * 抓取的URL是否已经存在
     * @param type $url 
     */
    private function isHas($url_table, $url) {
        $count = $url_table->where(array('url' => $url))->count();
        return 0 == $count;
    }

}

?>
